package com.wjz.commons.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wjz.commons.entity.bo.AjaxResult;
import com.wjz.commons.entity.bo.BasePage;
import com.wjz.commons.entity.vo.ModelVo;
import com.wjz.commons.enums.MasterConstants;
import com.wjz.commons.mapper.ModelVoMapper;
import com.wjz.commons.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author wjz
 * @date 2021/7/7 15:28
 */
@Slf4j
@Service
public class ModelApiService {

    @Autowired
    private ModelVoMapper modelVoMapper;

    @Autowired
    private FieldApiService fieldApiService;

    public Page<ModelVo> queryModelList(BasePage basePage, String label) {
        return modelVoMapper.selectPage(new Page<>(basePage.getCurrent(), basePage.getPageSize()),
                new LambdaQueryWrapper<ModelVo>().like(StrUtil.isNotEmpty(label), ModelVo::getLabel, label)
        );
    }

    public AjaxResult addModel(ModelVo modelVo) {
        Integer count = modelVoMapper.selectCount(new LambdaQueryWrapper<ModelVo>().eq(ModelVo::getLabel, modelVo.getLabel()));
        if (count > 0) {
            return ResultTool.fail("名称重复！");
        }
        long nextId = IdUtil.getSnowflake().nextId();
        modelVo.setGuid(nextId)
                .setStatus(MasterConstants.INIT)
                .setTemplate(false)
                .setCreateTime(new Date());
        modelVoMapper.insert(modelVo);
        return ResultTool.success();
    }

    public void deleteModel(Long objectId) {
        modelVoMapper.deleteById(objectId);
        fieldApiService.deleteByModelId(objectId);
    }

    public void update(ModelVo modelVo) {
        modelVoMapper.updateById(modelVo.setUpdateTime(new Date()));
    }

    public AjaxResult rename(ModelVo modelVo) {
        if (checkLabel(modelVo.getLabel())) {
            return ResultTool.fail("名称重复！");
        }
        modelVoMapper.updateById(modelVo);
        return ResultTool.success();
    }

    public boolean checkLabel(String label) {
        Integer count = modelVoMapper.selectCount(new LambdaQueryWrapper<ModelVo>().eq(ModelVo::getLabel, label));
        if (count > 0) {
            return true;
        }
        return false;
    }

    public ModelVo getModelByGuid(Long guid) {
        ModelVo modelVo = modelVoMapper.selectOne(new LambdaQueryWrapper<ModelVo>().eq(ModelVo::getGuid, guid));
        return modelVo;
    }
}
